﻿<%@ WebHandler Language="C#" Class="UploadFileSave" %>

using System;
using System.Web;
using DatabaseAccess.DBUtility;
using BusinessRule.DTO;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

public class UploadFileSave : IHttpHandler {
    private string importTempPath = System.Configuration.ConfigurationManager.AppSettings["ImportPath"];
    public void ProcessRequest (HttpContext context) {

        try
        {
            var action = context.Request["action"].ToString();
            switch (action)
            {
                case "saveRBConFiles":
                    SaveRBConFiles(context);
                    break;
                case "filesUnpack":
                    FilesUnpack(context);
                    break;
                case "replaceFiles":
                    ReplaceFiles(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception e)
        {
            var result = new uMESProcessResult()
            {
                Result = false,
                Message = e.Message
            };
            context.Response.Write(JsonConvert.SerializeObject(result));
            context.Response.StatusCode = 500;
            context.Response.Write(result);
        }

        
        
    }
    #region 文件替换

    /// <summary>
    /// 文件替换
    /// </summary>
    /// <param name="context"></param>
    public void ReplaceFiles(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        var sourceDirPath = context.Request["sourceDir"].ToString();//源
        var targetDirPath = context.Request["targetDir"].ToString();//目标
        var backDirPath = context.Request["backDir"].ToString();//备份

        var returnData = new Dictionary<string, List<string>>();
        returnData.Add("0",new List<string>());//失败的路径
        returnData.Add("1", new List<string>());//成功的路径

        if (Directory.Exists(backDirPath)) {
            backDirPath = backDirPath + "\\" + DateTime.Now.ToString("yyyyMMdd");
            Directory.CreateDirectory(backDirPath);
        }
        ReplaceFilesByDir(sourceDirPath, targetDirPath, backDirPath, ref returnData);

        result.Result = true;
        result.ReturnData = returnData;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 替换文件，及子文件夹
    /// </summary>
    /// <param name="sourceDirPath"></param>
    /// <param name="targetDirPath"></param>
    /// <param name="backUpDirPath"></param>
    /// <param name="returnData"></param>
    void ReplaceFilesByDir(string sourceDirPath, string targetDirPath, string backUpDirPath,ref Dictionary<string, List<string>> returnData)
    {
        var sourceDir = new DirectoryInfo(sourceDirPath);
        foreach (FileInfo fi in sourceDir.GetFiles())
        {
            if (!System.IO.Directory.Exists(targetDirPath))
            {
                returnData["0"].Add(targetDirPath+"\\"+fi.Name);
                continue;
            }
            //替换文件,替换前先备份
            if (File.Exists(targetDirPath + "\\" + fi.Name))
            {
                if (!Directory.Exists(backUpDirPath)) {
                    Directory.CreateDirectory(backUpDirPath);
                }
                File.Copy(targetDirPath + "\\" + fi.Name, backUpDirPath + "\\" + fi.Name, true);
            }
            //备份成功后替换
            File.Copy(sourceDirPath + "\\" + fi.Name, targetDirPath + "\\" + fi.Name, true);

            returnData["1"].Add(targetDirPath + "\\" + fi.Name);
        }

        foreach (DirectoryInfo dr in sourceDir.GetDirectories())
        {
            string sonDirName = dr.FullName.Replace(sourceDir.FullName, "");
            ReplaceFilesByDir(sourceDirPath + sonDirName, targetDirPath + sonDirName, backUpDirPath + sonDirName, ref returnData);
        }
    }
    
    #endregion

    #region 文件解压
    /// <summary>
    /// 文件解压
    /// </summary>
    /// <param name="context"></param>
    public void FilesUnpack(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        var files = context.Request.Files;
        if (files.Count == 0)
        {
            result.Message = "未上传文件";
            context.Response.StatusCode = 500;
            context.Response.Write(result);
            return;
        }
        var unpackDirName = context.Request["unpackDirName"].ToString();//解压的文件夹名

        //设置文件名
       var fileName = System.IO.Path.GetFileName(files[0].FileName);
       var extension = System.IO.Path.GetExtension(files[0].FileName);
       var tempPath = context.Server.MapPath(importTempPath) + unpackDirName + DateTime.Now.ToString("yyyyMMddHHmmssfff") + extension;
       files[0].SaveAs(tempPath);
        
       //解压文件，并把文件路径反馈前台
       var returnData =new Dictionary<string, List<string>>();
       List<string> returnFile = new List<string>();

       var unpackDirPath = context.Server.MapPath(importTempPath) + unpackDirName + DateTime.Now.ToString("yyyyMMddHHmmssfff");
       if (!System.IO.Directory.Exists(unpackDirPath))
       {
           System.IO.Directory.CreateDirectory(unpackDirPath);
       }
       UnZip(tempPath, unpackDirPath + "/", ref returnFile);

       returnData.Add(unpackDirPath, returnFile);
        result.Result = true;
        result.ReturnData = returnData;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 文件解压，获取html文件路径
    /// </summary>
    /// <param name="SrcFile"></param>
    /// <param name="DstFile"></param>
    /// <param name="BufferSize"></param>
    /// <param name="htmlurl"></param>
    private void UnZip(string SrcFile, string DstFile, ref List<string> returnFile)
    {
        
        bool isFinish = false;
        
        using (FileStream fileStreamIn = new FileStream(SrcFile, FileMode.Open, FileAccess.Read)) { 
            using(ICSharpCode.SharpZipLib.Zip.ZipInputStream zipInStream = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(fileStreamIn)){
                while (!isFinish)
                {
                    ICSharpCode.SharpZipLib.Zip.ZipEntry entry = zipInStream.GetNextEntry();
                    if (entry == null)
                    {
                        isFinish = true;
                        break;
                    }

                    string fileName = Path.Combine(DstFile, entry.Name);

                    //获取上级文件夹的个数，若有上级文件夹需要创建
                    if (entry.Name.LastIndexOf("/") > -1) {
                        var drNameList = entry.Name.Substring(0, entry.Name.LastIndexOf("/")).Split('/');
                        for (int i = 0; i < drNameList.Length; i++)
                        {
                            var drPath = "";
                            for (int j = 0; j <= i; j++)
                            {
                                if (string.IsNullOrWhiteSpace(drNameList[j]))
                                    continue;
                                drPath += drNameList[j] + "/";
                            }
                            if (!System.IO.Directory.Exists(DstFile + drPath))
                            {
                                System.IO.Directory.CreateDirectory(DstFile + drPath);
                            }
                        }
                    }
                    if (fileName.EndsWith("/") || fileName.EndsWith("\\"))
                    {
                        continue;
                    }
                    using (FileStream fileStreamOut = new FileStream(fileName, FileMode.Create, FileAccess.Write)) {

                        byte[] buffer = new byte[zipInStream.Length];
                        
                        zipInStream.Read(buffer, 0, buffer.Length);
                        fileStreamOut.Write(buffer, 0, buffer.Length );
                        
                        fileStreamOut.Dispose();
                    }
                    fileName = fileName.Replace("/","\\");
                    returnFile.Add(fileName);
                }
                zipInStream.Dispose();
                fileStreamIn.Dispose();

                zipInStream.Dispose();
                fileStreamIn.Dispose();
            }
        }
        

        
      
    }

    #endregion

    /// <summary>
    /// 保存热表的批次模板文件
    /// </summary>
    /// <param name="context"></param>
    public void SaveRBConFiles(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;
        
        string fileName = string.Empty;
        HttpFileCollection files = context.Request.Files;

        if (files.Count == 0)
        {
            result.Message = "未上传文件";
            context.Response.StatusCode = 500;
            context.Response.Write(result);
            return;
        }

        if (files.Count > 0)
        {
                //设置文件名
                fileName = System.IO.Path.GetFileName(files[0].FileName);
                //保存文件 
                files[0].SaveAs(context.Server.MapPath("../Temp/ReBiaoContainerTemplate/" + fileName));

                string sql = string.Format("SELECT * FROM rbcontainertemplatelist t WHERE t.filename='{0}'", fileName);

                string physicalpath = context.Request.PhysicalApplicationPath + "Temp\\ReBiaoContainerTemplate\\" + fileName;

                if (DatabaseHelper.Query_ReturnDatTable(sql).Rows.Count == 0)
                {
                    sql = string.Format("INSERT INTO rbcontainertemplatelist (filename,physicalpath,rbcontainertemplatelistid) VALUES('{0}','{1}','{2}')", fileName, physicalpath, Guid.NewGuid().ToString());
                    int i = DatabaseHelper.ExecuteSql(sql);
                }

                result.Message = "文件上传成功,fileName:" + fileName;
                context.Response.Write(result);
           
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}